//
// Created by root on 19-7-28.
//

#include "file_utils.h"
#include "log_utils.h"
#include<fstream>
#include<iostream>
#include <sstream>
#include <unistd.h>

using namespace std;

#define TAG "FileUtils"

#define NICE_NAME_LIST_PATH "/data/local/tmp/pvdnc_system_app.txt"
#define KEEP_ALIVE_LIST_PATH "/data/local/tmp/pvdnc_keep_alive.txt"

bool file_exist(const string &file_path) {
    return access(file_path.c_str(), F_OK | R_OK) == 0;
}

vector<string> read_lines(const string &file_path) {
    if (!file_exist(file_path))
        return vector<string>();
    ifstream in(file_path);
    vector<string> result;
    string line;
    while (getline(in, line)) {
        result.push_back(line);
        //LOGD("read line:%s\n",line.c_str());
    }
    in.close();
    return result;
}



bool contains(vector<string> u, const string &find){
    if(u.empty()){
        LOGE("fail to read u,use default rule\n");
        return find.find("pvdnc")!=string::npos;
    }
    for (auto itor = u.begin(); itor !=u.end(); ++itor) {
        if(itor->find(find)!=string::npos)//更少的包含字符也会判定为true
            return true;
    }
    return false;
}

bool nice_name_contains(string find){
    vector<string> lines=read_lines(NICE_NAME_LIST_PATH);
    return contains(lines,find);
}

bool keep_alive_contains(string find){
    vector<string> lines=read_lines(KEEP_ALIVE_LIST_PATH);
    return contains(lines,find);
}

void write_file(const std::string &file_path, const std::string &content) {
    ofstream os(file_path);
    os<<content;
    os.flush();
    os.close();
    if(!file_exist(file_path)){//权限不够
        string echo_cmd=string("su -c ");
        echo_cmd.append("\"");
        echo_cmd.append("echo \"");echo_cmd.append(content);echo_cmd.append("\"");
        echo_cmd.append(" > ");echo_cmd.append(file_path);
        echo_cmd.append("\"");
        int cmd_ret=system(echo_cmd.c_str());
        LOGD("use su to write file:%s -> cmd:%s ret:%d\n",file_path.c_str(),echo_cmd.c_str(),cmd_ret);
    }
}

std::string read_all(const std::string &file_path){
    ifstream is(file_path);
    if(!is)//文件不存在
        return string("");
    stringstream ss;
    ss<<is.rdbuf();
    string content= ss.str();
    is.close();
    return content;
}

